{% extends "templates/web.html" %}

{% block page_content %}

<style>
/* 基于TMS跟踪界面设计的OMS支付管理样式 */
.oms-payment-container {
    width: 100vw;
    height: 100vh;
    margin: 0;
    padding: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    background: #f8f9fa;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* 顶部操作区域 */
.payment-actions {
    background: white;
    padding: 20px;
    border-radius: 0;
    margin: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    gap: 15px;
    align-items: center;
    flex-shrink: 0;
}

.payment-actions .input-group {
    flex: 1;
    position: relative;
}

.payment-actions input, .payment-actions select {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e9ecef;
    border-radius: 6px;
    font-size: 16px;
    transition: border-color 0.3s;
}

.payment-actions input:focus, .payment-actions select:focus {
    outline: none;
    border-color: #007bff;
}

.payment-actions button {
    background: #dc3545;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
    font-weight: 600;
}

.payment-actions button:hover {
    background: #c82333;
}

.payment-actions button:disabled {
    background: #6c757d;
    cursor: not-allowed;
}

/* 状态筛选区域 */
.status-filter {
    background: white;
    padding: 15px 20px;
    border-radius: 0;
    margin: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
}

.filter-tabs {
    display: flex;
    gap: 20px;
    align-items: center;
}

.filter-tab {
    padding: 8px 16px;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-tab.active {
    background: #dc3545;
    color: white;
}

.filter-tab:not(.active) {
    background: #f8f9fa;
    color: #6c757d;
}

.filter-tab:not(.active):hover {
    background: #e9ecef;
    color: #495057;
}

.filter-tab .icon {
    font-size: 16px;
}

.export-btn {
    background: #dc3545;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
}

.export-btn:hover {
    background: #c82333;
}

/* 支付结果表格 */
.payment-results {
    background: white;
    border-radius: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    overflow: hidden;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.payment-table {
    width: 100%;
    border-collapse: collapse;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.payment-table thead {
    background: #28a745;
    color: white;
    flex-shrink: 0;
    display: table;
    width: 100%;
    table-layout: fixed;
}

.payment-table th {
    padding: 15px 12px;
    text-align: left;
    font-weight: 600;
    font-size: 14px;
}

.payment-table tbody {
    flex: 1;
    overflow-y: auto;
    display: block;
}

.payment-table tbody tr {
    border-bottom: 1px solid #e9ecef;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: table;
    width: 100%;
    table-layout: fixed;
}

.payment-table tbody tr:hover {
    background: #f8f9fa;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.payment-table tbody tr:active {
    transform: translateY(0);
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

.payment-table tbody tr.selected {
    background: #e8f5e8;
    border-left: 4px solid #28a745;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(40, 167, 69, 0.2);
}

.payment-table tbody tr.selected:hover {
    background: #d4edda;
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(40, 167, 69, 0.3);
}

.payment-table td {
    padding: 15px 12px;
    vertical-align: top;
}

.payment-id {
    font-weight: 600;
    color: #007bff;
    font-size: 14px;
}

.payment-amount {
    font-weight: 600;
    color: #28a745;
    font-size: 16px;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.pending {
    background: #fff3cd;
    color: #856404;
}

.status-badge.paid {
    background: #d4edda;
    color: #155724;
}

.status-badge.failed {
    background: #f8d7da;
    color: #721c24;
}

.status-badge.canceled {
    background: #d1ecf1;
    color: #0c5460;
}

.notification-pending {
    background: #fff3cd;
    color: #856404;
}

.notification-sent {
    background: #d4edda;
    color: #155724;
}

.notification-failed {
    background: #f8d7da;
    color: #721c24;
}

.action-btn {
    margin: 2px;
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 4px;
    border: 1px solid #dee2e6;
    background: white;
    color: #495057;
    cursor: pointer;
    transition: all 0.3s;
}

.action-btn:hover {
    background: #f8f9fa;
    border-color: #adb5bd;
}

.action-btn.btn-outline-primary:hover {
    background: #007bff;
    color: white;
}

.action-btn.btn-outline-success:hover {
    background: #28a745;
    color: white;
}

.action-btn.btn-outline-danger:hover {
    background: #dc3545;
    color: white;
}

.action-btn.btn-outline-warning {
    border-color: #ffc107;
    color: #ffc107;
}

.action-btn.btn-outline-warning:hover {
    background: #ffc107;
    color: white;
}

/* 展开的详细信息 */
.payment-detail {
    display: none;
    background: #f8f9fa;
    border-top: 1px solid #e9ecef;
    animation: slideDown 0.3s ease-out;
}

.payment-detail.expanded {
    display: table-row;
    animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
    from {
        opacity: 0;
        max-height: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        max-height: 500px;
        transform: translateY(0);
    }
}

.detail-actions {
    padding: 15px 20px;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    gap: 10px;
}

.detail-btn {
    background: #6c757d;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
}

.detail-btn:hover {
    background: #5a6268;
}

.detail-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 20px;
    padding: 20px;
}

.timeline-section h4 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
}

.timeline-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;
    position: relative;
    padding-left: 20px;
}

.timeline-item:not(:last-child)::before {
    content: '';
    position: absolute;
    left: 8px;
    top: 20px;
    bottom: -15px;
    width: 2px;
    background: #e9ecef;
}

.timeline-item::after {
    content: '';
    position: absolute;
    left: 6px;
    top: 16px;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #6c757d;
}

.timeline-content {
    flex: 1;
}

.timeline-time {
    font-size: 13px;
    color: #6c757d;
    margin-bottom: 4px;
}

.timeline-event {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.timeline-location {
    font-size: 13px;
    color: #6c757d;
    margin-top: 4px;
}

.sidebar-section h4 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
}

.info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
}

.info-row:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.info-label {
    color: #6c757d;
    font-size: 13px;
}

.info-value {
    color: #333;
    font-size: 13px;
    font-weight: 500;
}

.info-value a {
    color: #007bff;
    text-decoration: none;
}

.info-value a:hover {
    text-decoration: underline;
}

/* 加载和错误状态 */
.loading {
    text-align: center;
    padding: 40px;
    color: #6c757d;
}

.error {
    background: #f8d7da;
    color: #721c24;
    padding: 15px;
    border-radius: 6px;
    margin: 20px 0;
    border: 1px solid #f5c6cb;
}

/* 选中项操作区域 */
.selected-actions {
    background: #e3f2fd;
    border: 2px solid #2196f3;
    border-radius: 8px;
    padding: 15px 20px;
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 8px rgba(33, 150, 243, 0.2);
}

.selected-info {
    font-weight: 600;
    color: #1976d2;
    font-size: 16px;
}

.selected-buttons {
    display: flex;
    gap: 10px;
    align-items: center;
}

.btn-primary, .btn-secondary, .btn-danger, .btn-success, .btn-info {
    padding: 8px 16px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 6px;
}

.btn-primary {
    background: #007bff;
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-success:hover {
    background: #1e7e34;
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
}

.btn-primary:disabled, .btn-secondary:disabled, .btn-danger:disabled, .btn-success:disabled, .btn-info:disabled {
    background: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
}

/* 表格复选框样式 */
.payment-table input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .oms-payment-container {
        padding: 0;
    }
    
    .payment-actions {
        flex-direction: column;
        padding: 15px;
    }
    
    .status-filter {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
        padding: 15px;
    }
    
    .filter-tabs {
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .detail-content {
        grid-template-columns: 1fr;
    }
    
    .payment-table {
        font-size: 12px;
    }
    
    .payment-table th,
    .payment-table td {
        padding: 10px 8px;
    }
}
</style>

<div class="oms-payment-container">
    
    <!-- 顶部操作区域 -->
    <div class="payment-actions">
        <button id="refreshBtn" class="btn-secondary">
            <i class="fa fa-refresh"></i> 刷新
        </button>
        <button id="deleteSelectedBtn" class="btn-danger" disabled>
            <i class="fa fa-trash"></i> 删除选中
        </button>
        <button id="newRecordBtn" class="btn-info" onclick="openNewRecord()">
            <i class="fa fa-file-o"></i> 新建记录
        </button>
    </div>

    <!-- 状态筛选区域 -->
    <div class="status-filter">
        <div class="filter-tabs">
            <div class="filter-tab active" data-status="all">
                <span class="icon">💳</span>
                <span>全部(<span id="allCount">0</span>)</span>
            </div>
            <div class="filter-tab" data-status="pending">
                <span class="icon">⏳</span>
                <span>待支付(<span id="pendingCount">0</span>)</span>
            </div>
            <div class="filter-tab" data-status="paid">
                <span class="icon">✅</span>
                <span>已支付(<span id="paidCount">0</span>)</span>
            </div>
            <div class="filter-tab" data-status="failed">
                <span class="icon">❌</span>
                <span>支付失败(<span id="failedCount">0</span>)</span>
            </div>
        </div>
        <button class="export-btn" id="exportBtn">
            <span>📋</span>
            <span>导出数据</span>
        </button>
    </div>

    <!-- 支付结果表格 -->
    <div id="paymentResults" class="payment-results" style="display: none;">
        <table class="payment-table">
            <thead>
                <tr>
                    <th width="50px">
                        <input type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll()">
                    </th>
                    <th>支付ID</th>
                    <th>买家ID</th>
                    <th>金额</th>
                    <th>货币</th>
                    <th>支付状态</th>
                    <th>通知状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="paymentTableBody">
                <!-- 支付结果将通过JavaScript动态生成 -->
            </tbody>
        </table>
    </div>

    <!-- 加载状态 -->
    <div id="loadingState" class="loading" style="display: none;">
        <p>正在加载支付数据...</p>
    </div>

    <!-- 错误状态 -->
    <div id="errorState" class="error" style="display: none;">
        <p id="errorMessage">加载失败，请稍后重试</p>
    </div>

    <!-- 选中项操作区域 -->
    <div id="selectedActions" class="selected-actions" style="display: none;">
        <div class="selected-info">
            <span id="selectedCount">0</span> 项已选中
        </div>
        <div class="selected-buttons">
            <button id="paySelectedBtn" class="btn-success">
                <i class="fa fa-credit-card"></i> 支付选中项
            </button>
            <button id="checkStatusSelectedBtn" class="btn-info">
                <i class="fa fa-refresh"></i> 检查状态
            </button>
            <button id="deleteSelectedBtn2" class="btn-danger">
                <i class="fa fa-trash"></i> 删除选中
            </button>
            <button id="clearSelectionBtn" class="btn-secondary">
                <i class="fa fa-times"></i> 取消选择
            </button>
        </div>
    </div>
</div>

<!-- 40Seas Payment SDK -->
<script src="https://cdn.40seas.com/v1/sdk.js"></script>

<script>
// 全局变量
let paymentData = [];
let currentFilter = 'all';

// 40Seas 支付相关变量
let _40Seas = null;
let currentPaymentToken = null;
let currentCheckoutId = null;

// 初始化 40Seas SDK
async function init40SeasSDK() {
    if (typeof window._40Seas !== 'undefined') {
        _40Seas = window._40Seas;
        return Promise.resolve();
    }
    
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = 'https://cdn.40seas.com/v1/sdk.js';
        script.onload = () => {
            _40Seas = window._40Seas;
            resolve();
        };
        script.onerror = () => {
            reject(new Error('Failed to load 40Seas SDK'));
        };
        document.head.appendChild(script);
    });
}

// 打开支付模态框
async function openPaymentModal() {
    try {
        
        if (!currentPaymentToken) {
            throw new Error('支付令牌不存在');
        }
        
        // 确保SDK已加载
        await init40SeasSDK();
        
        if (!_40Seas) {
            throw new Error('40Seas SDK未加载');
        }
        
        
        // 定义主题样式
        const theme = {
            '.Title': {
                fontSize: '20px',
                color: '#2c3e50',
                fontWeight: 'bold'
            },
            '.Button': {
                backgroundColor: '#3498db',
                color: 'white',
                borderRadius: '6px',
                padding: '12px 24px',
                fontSize: '16px',
                fontWeight: 'bold'
            },
            '.Button:hover': {
                backgroundColor: '#2980b9'
            },
            '.Subtitle': {
                color: '#7f8c8d',
                fontSize: '14px'
            },
            '.SummaryText': {
                backgroundColor: '#ecf0f1',
                padding: '15px',
                borderRadius: '6px',
                fontSize: '14px'
            }
        };
        
        // 定义选项 - 强制全款支付
        const options = {
            checkout: {
                paymentMethodTypes: ['card', 'ach', 'wire'],
                paymentTerms: ['immediate'],
                allowPartialPayments: false,  // 禁止部分支付
                requireFullPayment: true      // 要求全额支付
            },
            skipSuccessUponConfirmation: true
        };
        
        // 定义回调函数
        const callbacks = {
            onConfirm: (payload) => {
                handlePaymentSuccess(payload);
            },
            onCancel: (payload) => {
                handlePaymentCancel(payload);
            }
        };
        
        // 打开支付模态框
        _40Seas.open(currentPaymentToken, callbacks, options, theme);
        
    } catch (error) {
        console.error('打开支付模态框失败:', error);
        alert('Unable to open payment interface: ' + error.message);
    }
}

// 处理支付成功
function handlePaymentSuccess(payload) {
    
    // 关闭支付模态框
    if (_40Seas) {
        _40Seas.close();
    }
    
    // 显示成功信息
    alert(`Payment successful! Amount: $${payload.amount} ${payload.currency}`);
    
    // 调用后端API处理支付成功
    frappe.call({
        method: 'upsystem.upsystem.api_payment.handle_payment_success',
        args: {
            checkout_id: currentCheckoutId,
            payment_data: payload
        },
        callback: function(response) {
            if (response.message && response.message.success) {
                // 刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 2000);
            } else {
                console.error('支付处理失败:', response.message?.error);
            }
        }
    });
}

// 处理支付取消
function handlePaymentCancel(payload) {
    
    // 关闭支付模态框
    if (_40Seas) {
        _40Seas.close();
    }
    
    // 显示取消信息 - 对于强制全款支付，取消意味着可以重新支付
    alert('Payment cancelled. You can retry payment anytime.');
}
let selectedItems = new Set();

// 初始化支付管理页面
document.addEventListener('DOMContentLoaded', function() {
    
    // 清除所有测试数据
    paymentData = [];
    clearAllResults();
    
    bindEvents();
    loadPaymentData();
});

// 清除所有结果显示
function clearAllResults() {
    // 隐藏结果表格
    const resultsDiv = document.getElementById('paymentResults');
    if (resultsDiv) {
        resultsDiv.style.display = 'none';
    }
    
    // 清空表格内容
    const tableBody = document.getElementById('paymentTableBody');
    if (tableBody) {
        tableBody.innerHTML = '';
    }
    
    // 重置状态计数
    updateStatusCounts();
}

// 绑定事件
function bindEvents() {
    // 创建支付按钮
    const createPaymentBtn = document.getElementById('createPaymentBtn');
    if (createPaymentBtn) {
        createPaymentBtn.addEventListener('click', handleCreatePayment);
    }

    // 刷新按钮
    const refreshBtn = document.getElementById('refreshBtn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', loadPaymentData);
    }

    // 状态筛选标签
    const filterTabs = document.querySelectorAll('.filter-tab');
    filterTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const status = this.dataset.status;
            setActiveFilter(status);
            filterPaymentResults(status);
        });
    });

    // 导出按钮
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', handleExport);
    }

    // 删除选中按钮
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    if (deleteSelectedBtn) {
        deleteSelectedBtn.addEventListener('click', handleDeleteSelected);
    }

    // 选中项操作按钮
    const paySelectedBtn = document.getElementById('paySelectedBtn');
    if (paySelectedBtn) {
        paySelectedBtn.addEventListener('click', handlePaySelected);
    }

    const checkStatusSelectedBtn = document.getElementById('checkStatusSelectedBtn');
    if (checkStatusSelectedBtn) {
        checkStatusSelectedBtn.addEventListener('click', handleCheckStatusSelected);
    }

    const deleteSelectedBtn2 = document.getElementById('deleteSelectedBtn2');
    if (deleteSelectedBtn2) {
        deleteSelectedBtn2.addEventListener('click', handleDeleteSelected);
    }

    const clearSelectionBtn = document.getElementById('clearSelectionBtn');
    if (clearSelectionBtn) {
        clearSelectionBtn.addEventListener('click', clearSelection);
    }
}

// 显示加载状态
function showLoading() {
    document.getElementById('paymentResults').style.display = 'none';
    document.getElementById('errorState').style.display = 'none';
    document.getElementById('loadingState').style.display = 'block';
}

// 显示错误信息
function showError(message) {
    
    let errorText = message;
    if (typeof message === 'object') {
        errorText = JSON.stringify(message, null, 2);
    }
    
    document.getElementById('paymentResults').style.display = 'none';
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('errorState').style.display = 'block';
    document.getElementById('errorMessage').textContent = errorText;
}

// 显示支付结果
function showPaymentResults() {
    
    // 隐藏加载和错误状态
    const loadingState = document.getElementById('loadingState');
    const errorState = document.getElementById('errorState');
    const paymentResults = document.getElementById('paymentResults');
    
    
    if (loadingState) loadingState.style.display = 'none';
    if (errorState) errorState.style.display = 'none';

    // 生成表格行
    generatePaymentTable();

    // 显示结果
    if (paymentResults) {
        paymentResults.style.display = 'block';
    }
}

// 生成支付表格
function generatePaymentTable() {
    const tbody = document.getElementById('paymentTableBody');
    
    if (!tbody) {
        return;
    }
    
    tbody.innerHTML = '';

    if (paymentData.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="text-center text-muted">
                    <i class="fa fa-inbox"></i> 暂无数据
                </td>
            </tr>
        `;
        return;
    }
    

    paymentData.forEach((payment, paymentIndex) => {
        const row = document.createElement('tr');
        row.className = 'payment-row';
        row.dataset.status = payment.status;
        row.dataset.index = paymentIndex;
        
        row.innerHTML = `
            <td>
                <input type="checkbox" class="row-checkbox" data-payment-id="${payment.name}" onchange="toggleRowSelection('${payment.name}')">
            </td>
            <td>
                <div class="payment-id">${payment.name}</div>
            </td>
            <td>${payment.buyer_id || '-'}</td>
            <td>
                <div class="payment-amount">$${payment.amount || 0}</div>
            </td>
            <td>${payment.currency || '-'}</td>
            <td>
                <div class="status-badge ${payment.status || 'pending'}">
                    <span>${getStatusIcon(payment.status)}</span>
                    <span>${getStatusText(payment.status)}</span>
                </div>
            </td>
            <td>
                <div class="status-badge notification-${payment.notification_status || 'pending'}">
                    <span>${getNotificationStatusIcon(payment.notification_status)}</span>
                    <span>${getNotificationStatusText(payment.notification_status)}</span>
                </div>
            </td>
            <td>${formatDate(payment.creation)}</td>
            <td>
                <button class="action-btn btn-outline-primary" onclick="viewPaymentDetail('${payment.name}')">
                    <i class="fa fa-eye"></i> 查看
                </button>
                <button class="action-btn btn-outline-info" onclick="editPayment('${payment.name}')">
                    <i class="fa fa-edit"></i> 编辑
                </button>
                <button class="action-btn btn-outline-warning" onclick="initiate40ssPayment('${payment.name}')">
                    <i class="fa fa-credit-card"></i> 40ss支付
                </button>
                <button class="action-btn btn-outline-info" onclick="create40ssPayable('${payment.name}')">
                    <i class="fa fa-plus-circle"></i> 创建40ss应付
                </button>
                <button class="action-btn btn-outline-danger" onclick="sendEmailNotification('${payment.name}')">
                    <i class="fa fa-envelope"></i> 发送邮件
                </button>
            </td>
        `;

        // 添加点击事件
        row.addEventListener('click', function(e) {
            if (!e.target.closest('button')) {
                togglePaymentDetail(paymentIndex);
            }
        });
        
        tbody.appendChild(row);
    });
}

// 切换支付详情显示
function togglePaymentDetail(index) {
    if (index === undefined || index === null || isNaN(index)) {
        return;
    }
    
    const rows = document.querySelectorAll('.payment-row');
    const detailRows = document.querySelectorAll('.payment-detail');
    
    // 移除所有选中状态
    rows.forEach(row => row.classList.remove('selected'));
    detailRows.forEach(row => row.classList.remove('expanded'));
    
    // 选中当前行
    const selector = '.payment-row[data-index="' + index + '"]';
    const detailSelector = '.payment-detail[data-index="' + index + '"]';
    
    const currentRow = document.querySelector(selector);
    const currentDetail = document.querySelector(detailSelector);
    
    if (currentRow && currentDetail) {
        currentRow.classList.add('selected');
        currentDetail.classList.add('expanded');
    }
}

// 设置活动筛选器
function setActiveFilter(status) {
    const filterTabs = document.querySelectorAll('.filter-tab');
    filterTabs.forEach(tab => {
        tab.classList.remove('active');
        if (tab.dataset.status === status) {
            tab.classList.add('active');
        }
    });
    currentFilter = status;
}

// 筛选支付结果
function filterPaymentResults(status) {
    const rows = document.querySelectorAll('.payment-row');
    
    rows.forEach(row => {
        const rowStatus = row.dataset.status;
        if (status === 'all' || rowStatus === status) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

// 更新状态计数
function updateStatusCounts() {
    const counts = {
        all: paymentData.length,
        pending: 0,
        paid: 0,
        failed: 0
    };

    paymentData.forEach(payment => {
        if (counts.hasOwnProperty(payment.status)) {
            counts[payment.status]++;
        }
    });

    // 更新UI计数
    Object.keys(counts).forEach(status => {
        const element = document.getElementById(status + 'Count');
        if (element) {
            element.textContent = counts[status];
        }
    });
}

// 获取状态图标
function getStatusIcon(status) {
    const iconMap = {
        'pending': '⏳',
        'paid': '✅',
        'failed': '❌'
    };
    return iconMap[status] || '❓';
}

function getNotificationStatusIcon(status) {
    const iconMap = {
        'pending': '⏳',
        'sent': '✅',
        'failed': '❌'
    };
    return iconMap[status] || '❓';
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'pending': 'Pending Payment',
        'paid': 'Paid',
        'failed': 'Payment Failed'
    };
    return statusMap[status] || status;
}

function getNotificationStatusText(status) {
    const statusMap = {
        'pending': '待通知',
        'sent': '已通知',
        'failed': '通知失败'
    };
    return statusMap[status] || status;
}

// 格式化日期
function formatDate(dateString) {
    return new Date(dateString).toLocaleString('zh-CN');
}

// 处理创建支付
async function handleCreatePayment() {
    const buyerId = document.getElementById('buyerIdInput').value.trim();
    const amount = parseFloat(document.getElementById('amountInput').value);
    const currency = document.getElementById('currencySelect').value;
    
    if (!buyerId) {
        showError('请输入买家ID');
        return;
    }
    
    if (!amount || amount <= 0) {
        showError('请输入有效的支付金额');
        return;
    }
    
    try {
        showLoading();
        
        
        // 直接创建OMS Payment DocType记录
        const response = await frappe.call({
            method: 'frappe.client.insert',
            args: {
                doc: {
                    doctype: 'oms_payment',
                    buyer_id: buyerId,
                    amount: amount,
                    currency: currency,
                    payment_channel: '40ss',
                    status: 'pending',
                    notification_status: 'pending',
                    company: 'flowa (Demo)'
                }
            }
        });
        
        
        if (response.message) {
            // 清空输入框
            document.getElementById('buyerIdInput').value = '';
            document.getElementById('amountInput').value = '';
            
            // 刷新数据
            loadPaymentData();
            
            alert('OMS Payment record created successfully!');
        } else {
            showError('创建支付失败: ' + (response.message?.error || '未知错误'));
        }
    } catch (error) {
        console.error('Create payment error:', error);
        showError('创建支付失败: ' + error.message);
    }
}

// 加载支付数据
async function loadPaymentData() {
    
    try {
        showLoading();
        
        
        // 使用正确的DocType名称：oms_payment
        const response = await frappe.call({
            method: 'frappe.client.get_list',
            args: {
                doctype: 'oms_payment',
                fields: ['name', 'buyer_id', 'amount', 'currency', 'status', 'notification_status', 'creation', 'modified'],
                limit: 100,
                offset: 0
            }
        });
        
        
        if (response.message) {
            // 直接查询DocType返回的是数组
            paymentData = response.message || [];
            
            showPaymentResults();
            updateStatusCounts();
        } else {
            showError('加载数据失败: ' + (response.message?.error || '未知错误'));
        }
    } catch (error) {
        console.error('Load payment data error:', error);
        console.error('错误堆栈:', error.stack);
        showError('加载数据失败: ' + error.message);
    }
    
}

// 查看支付详情
async function viewPaymentDetail(paymentId) {
    try {
        // 打开Frappe的DocType详情页面
        window.open(`/app/oms_payment/${paymentId}`, '_blank');
    } catch (error) {
        console.error('打开详情页面失败:', error);
        alert('Failed to open detail page: ' + error.message);
    }
}

// 编辑支付记录
async function editPayment(paymentId) {
    try {
        // 打开Frappe的DocType编辑页面
        window.open(`/app/oms_payment/${paymentId}/edit`, '_blank');
    } catch (error) {
        console.error('打开编辑页面失败:', error);
        alert('Failed to open edit page: ' + error.message);
    }
}

// 打开支付页面
async function openPaymentPage(paymentId) {
    try {
        const response = await frappe.call({
            method: 'upsystem.upsystem.api_payment.get_payment_detail',
            args: { payment_id: paymentId }
        });
        
        if (response.message && response.message.success) {
            const payment = response.message.data;
            
            // 如果有支付URL，优先使用40ss支付模态框
            if (payment.payment_token && typeof openPaymentModal === 'function') {
                // 设置当前支付令牌
                window.currentPaymentToken = payment.payment_token;
                window.currentCheckoutId = payment.checkout_id;
                
                // 打开40ss支付模态框
                await openPaymentModal();
            } else if (payment.payment_url) {
                // 回退到打开新窗口
                window.open(payment.payment_url, '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
            } else {
                alert('No payment method available for this payment');
            }
        } else {
            alert('Failed to get payment information: ' + (response.message?.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Open payment page error:', error);
        alert('Failed to get payment information: ' + error.message);
    }
}

// 检查支付状态
async function sendEmailNotification(paymentId) {
    try {
        
        // 获取公司列表供用户选择
        const companyResponse = await frappe.call({
            method: 'frappe.client.get_list',
            args: {
                doctype: 'Company',
                fields: ['name', 'company_name'],
                limit_page_length: 100
            }
        });
        
        if (!companyResponse.message || companyResponse.message.length === 0) {
            alert('No available companies found');
            return;
        }
        
        // 创建公司选择对话框
        const companyOptions = companyResponse.message.map(company => 
            `<option value="${company.name}">${company.company_name || company.name}</option>`
        ).join('');
        
        const selectedCompany = prompt(`请选择要发送邮件的公司:\n\n${companyResponse.message.map(company => 
            `${company.name}: ${company.company_name || company.name}`
        ).join('\n')}\n\n请输入公司名称:`, companyResponse.message[0].name);
        
        if (!selectedCompany) {
            return;
        }
        
        // 发送邮件通知
        const response = await frappe.call({
            method: 'upsystem.upsystem.api_payment.send_email_notification',
            args: {
                payment_id: paymentId,
                company: selectedCompany
            }
        });
        
        if (response.message && response.message.success) {
            alert(`Email notification sent successfully!\nSend count: ${response.message.send_count}\nNotification status: ${response.message.notification_status}`);
            // 刷新数据
            loadPaymentData();
        } else {
            alert('Failed to send email notification: ' + (response.message?.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Send email notification error:', error);
        alert('Failed to send email notification: ' + error.message);
    }
}

// 处理导出
function handleExport() {
    if (paymentData.length === 0) {
        alert('No data to export');
        return;
    }

    // 生成CSV数据
    const csvData = generateCSV();
    
    // 创建下载链接
    const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `payment_results_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 生成CSV数据
function generateCSV() {
    const headers = ['支付ID', '买家ID', '金额', '货币', '支付状态', '通知状态', '创建时间'];
    const rows = paymentData.map(payment => [
        payment.name,
        payment.buyer_id || '-',
        payment.amount || 0,
        payment.currency || '-',
        getStatusText(payment.status),
        getNotificationStatusText(payment.notification_status),
        formatDate(payment.creation)
    ]);

    const csvContent = [headers, ...rows]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');

    return csvContent;
}

// 全选/取消全选
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    
    rowCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
        const paymentId = checkbox.dataset.paymentId;
        if (selectAllCheckbox.checked) {
            selectedItems.add(paymentId);
        } else {
            selectedItems.delete(paymentId);
        }
    });
    
    updateSelectedActions();
}

// 切换行选择
function toggleRowSelection(paymentId) {
    const checkbox = document.querySelector(`.row-checkbox[data-payment-id="${paymentId}"]`);
    
    if (checkbox.checked) {
        selectedItems.add(paymentId);
    } else {
        selectedItems.delete(paymentId);
    }
    
    // 更新全选复选框状态
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    const checkedCount = document.querySelectorAll('.row-checkbox:checked').length;
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    
    if (checkedCount === 0) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = false;
    } else if (checkedCount === rowCheckboxes.length) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = true;
    } else {
        selectAllCheckbox.indeterminate = true;
    }
    
    updateSelectedActions();
}

// 更新选中项操作区域
function updateSelectedActions() {
    const selectedActions = document.getElementById('selectedActions');
    const selectedCount = document.getElementById('selectedCount');
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    
    if (selectedItems.size > 0) {
        selectedActions.style.display = 'flex';
        selectedCount.textContent = selectedItems.size;
        deleteSelectedBtn.disabled = false;
    } else {
        selectedActions.style.display = 'none';
        deleteSelectedBtn.disabled = true;
    }
}

// 清除选择
function clearSelection() {
    selectedItems.clear();
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    
    rowCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    
    selectAllCheckbox.checked = false;
    selectAllCheckbox.indeterminate = false;
    
    updateSelectedActions();
}

// 处理支付选中项
async function handlePaySelected() {
    if (selectedItems.size === 0) {
        alert('Please select items to pay first');
        return;
    }
    
    const selectedPayments = Array.from(selectedItems);
    const pendingPayments = selectedPayments.filter(id => {
        const payment = paymentData.find(p => p.name === id);
        return payment && payment.status === 'pending';
    });
    
    if (pendingPayments.length === 0) {
        alert('No pending payment records in selected items');
        return;
    }
    
    if (!confirm(`确定要支付 ${pendingPayments.length} 个选中项吗？`)) {
        return;
    }
    
    try {
        // 如果只有一个待支付项，直接使用40ss支付
        if (pendingPayments.length === 1) {
            await initiate40ssPayment(pendingPayments[0]);
        } else {
            // 多个待支付项，询问用户选择支付方式
            const use40ss = confirm(`您选择了 ${pendingPayments.length} 个待支付项。\n\n点击"确定"使用40ss支付（推荐）\n点击"取消"使用传统支付方式`);
            
            if (use40ss) {
                // 使用40ss支付第一个，其他等待
                for (let i = 0; i < pendingPayments.length; i++) {
                    if (i === 0) {
                        await initiate40ssPayment(pendingPayments[i]);
                    } else {
                        // 等待用户完成当前支付
                        await new Promise(resolve => setTimeout(resolve, 2000));
                        await initiate40ssPayment(pendingPayments[i]);
                    }
                }
            } else {
                // 使用传统支付方式
                for (const paymentId of pendingPayments) {
                    await openPaymentPage(paymentId);
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }
        }
        
        // 刷新数据
        setTimeout(() => {
            loadPaymentData();
            clearSelection();
        }, 2000);
        
    } catch (error) {
        console.error('Pay selected error:', error);
        alert('Payment operation failed: ' + error.message);
    }
}

// 处理检查选中项状态
async function handleCheckStatusSelected() {
    if (selectedItems.size === 0) {
        alert('Please select items to check first');
        return;
    }
    
    const selectedPayments = Array.from(selectedItems);
    
    try {
        for (const paymentId of selectedPayments) {
            await checkPaymentStatus(paymentId);
        }
        
        // 刷新数据
        setTimeout(() => {
            loadPaymentData();
            clearSelection();
        }, 2000);
        
    } catch (error) {
        console.error('Check status selected error:', error);
        alert('Failed to check status: ' + error.message);
    }
}

// 处理删除选中项
async function handleDeleteSelected() {
    if (selectedItems.size === 0) {
        alert('Please select items to delete first');
        return;
    }
    
    const selectedPayments = Array.from(selectedItems);
    
    if (!confirm(`确定要删除 ${selectedPayments.length} 个选中项吗？此操作不可恢复！`)) {
        return;
    }
    
    try {
        for (const paymentId of selectedPayments) {
            await deletePayment(paymentId);
        }
        
        // 刷新数据
        loadPaymentData();
        clearSelection();
        
    } catch (error) {
        console.error('Delete selected error:', error);
        alert('Delete operation failed: ' + error.message);
    }
}

// 删除单个支付
async function deletePayment(paymentId) {
    try {
        const response = await frappe.call({
            method: 'upsystem.upsystem.api_payment.delete_payment',
            args: { payment_id: paymentId }
        });
        
        if (response.message && response.message.success) {
            console.log(`Payment ${paymentId} deleted successfully`);
        } else {
            throw new Error(response.message?.error || '删除失败');
        }
    } catch (error) {
        console.error('Delete payment error:', error);
        throw error;
    }
}

// 打开新建记录页面
function openNewRecord() {
    console.log('打开新建OMS Payment记录页面');
    // 跳转到Frappe的DocType表单页面
    window.open('/app/oms_payment/new', '_blank');
}

// 启动40ss支付
async function initiate40ssPayment(paymentId) {
    console.log('===== 启动40ss支付 =====');
    console.log('支付ID:', paymentId);
    
    try {
        // 1. 获取支付记录详情
        const response = await frappe.call({
            method: 'frappe.client.get',
            args: {
                doctype: 'oms_payment',
                name: paymentId
            }
        });
        
        if (!response.message) {
            throw new Error('获取支付记录失败');
        }
        
        const payment = response.message;
        console.log('支付记录:', payment);
        console.log('支付状态:', payment.status, '类型:', typeof payment.status);
        
        // 2. 检查必要字段
        if (!payment.buyer_id || !payment.amount) {
            alert('Payment record missing required information (buyer ID or amount)');
            return;
        }
        
        // 3. 检查40ss SDK是否已加载
        if (typeof window._40Seas === 'undefined') {
            console.log('40ss SDK未加载，尝试加载...');
            await init40SeasSDK();
        }
        
        if (typeof window._40Seas === 'undefined') {
            throw new Error('40ss SDK加载失败');
        }
        
        // 4. 创建支付意图（如果还没有payment_token）
        let paymentToken = payment.payment_token;
        if (!paymentToken) {
            console.log('创建支付意图...');
            const createResponse = await frappe.call({
                method: 'upsystem.upsystem.api_payment.create_payment',
                args: {
                    buyer_id: payment.buyer_id,
                    amount: payment.amount,
                    currency: payment.currency || 'USD',
                    payment_channel: '40ss',
                    paytype: 'immediate'
                }
            });
            
            if (createResponse.message && createResponse.message.payment_token) {
                paymentToken = createResponse.message.payment_token;
                console.log('支付令牌创建成功:', paymentToken);
            } else {
                throw new Error('创建支付意图失败');
            }
        }
        
        // 5. 设置全局支付信息
        currentPaymentToken = paymentToken;
        currentCheckoutId = payment.checkout_id;
        window.currentPaymentToken = paymentToken;
        window.currentCheckoutId = payment.checkout_id;
        window.currentPaymentId = paymentId;
        
        // 6. 打开40ss支付模态框
        console.log('打开40ss支付模态框...');
        await openPaymentModal();
        
    } catch (error) {
        console.error('40ss支付启动失败:', error);
        alert('Failed to start 40ss payment: ' + error.message);
    }
}

// 创建40ss应付
async function create40ssPayable(paymentId) {
    console.log('===== 创建40ss应付 =====');
    console.log('支付ID:', paymentId);
    console.log('支付ID类型:', typeof paymentId);
    
    // 检查当前支付数据
    console.log('当前支付数据:', paymentData);
    const currentPayment = paymentData.find(p => p.name === paymentId);
    console.log('找到的支付记录:', currentPayment);
    
    try {
        // 直接调用API创建40ss应付
        const payableResponse = await frappe.call({
            method: 'upsystem.upsystem.api_payment.create_40ss_payable',
            args: {
                payment_id: paymentId
            }
        });
        
        console.log('API响应:', payableResponse);
        
        if (payableResponse.message && payableResponse.message.success) {
            alert('40ss payable created successfully!\nCheckout ID: ' + payableResponse.message.checkout_id + '\nPayment token: ' + payableResponse.message.payment_token);
            // 刷新数据
            loadPaymentData();
        } else {
            throw new Error(payableResponse.message?.error || '创建40ss应付失败');
        }
        
    } catch (error) {
        console.error('创建40ss应付失败:', error);
        alert('Failed to create 40ss payable: ' + error.message);
    }
}
</script>
{% endblock %}
